package com.xbjtech.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;
import com.xbjtech.model.Shop;
import com.xbjtech.model.beans.Result;
import com.xbjtech.realm.CustomRealm;
import com.xbjtech.service.ShopService;

@Controller
@RequestMapping("/shop")
public class ShopController {
	
	@Autowired
	ShopService shopService;

	@RequestMapping("/list")
	public String list() {
		return "shop/list";
	}
	
	
	@GetMapping("/data")
	@ResponseBody
	public Map<String, Object> data(
			@RequestParam(value = "page", required = false, defaultValue = "1")
			Integer page,
			@RequestParam(value = "rows", required = false, defaultValue = "10")
			Integer rows
			) {
		PageInfo<Shop> shops = shopService.selectByExamplePage(page, rows, null);
		Map<String, Object> map = new HashMap<>();
		map.put("total", shops.getTotal());
		map.put("rows", shops.getList());
		return map;
	}
	
	@PostMapping(value = "/save", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Result save(@Validated Shop shop, Errors errors) {
		// 服务器端校验
		// errors还需要处理一下
		try {
			if (null == shop.getId()) {
				shopService.insertWithoutPrimaryKey(shop);
			} else {
				shopService.updateByPrimaryKey(shop);
			}
			return Result.success();
		} catch (Exception e) {
		}
		return Result.fail();
	}
	
	@Autowired
	CustomRealm customRealm;
	
	@GetMapping("/del")
	@ResponseBody
	public Result del(
			@RequestParam(value = "id", required = true)
			Integer id) {
		try {
			shopService.deleteByPrimaryKey(id);
			return Result.success();
		} catch (Exception e) {
		}
		return Result.fail();
	}
}
